package com.wangshouyu.mp.base.request;

import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.Optional;

/**
 * @author 王守钰
 * @date 2020年12月06日 20:30
 * @description 微信公众号请求
 */
public class RequestBody implements Serializable {

    private transient Charset encoding;

    private byte[] data;

    private boolean isFile;

    private String fileName;

    public RequestBody() {
        super();
    }

    private RequestBody(byte[] data) {
        this.data = data;
    }

    private RequestBody(byte[] data, Charset encoding) {
        this.data = data;
        this.encoding = encoding;
    }

    public RequestBody(byte[] data, String fileName) {
        this.data = data;
        this.isFile = Boolean.TRUE;
        this.fileName = fileName;
    }

    public Optional<Charset> getEncoding() {
        return Optional.ofNullable(this.encoding);
    }

    public int length() {
        /* calculate the content length based on the data provided */
        return data != null ? data.length : 0;
    }

    public byte[] asBytes() {
        return data;
    }

    public String asString() {
        return !isBinary()
                ? new String(data, encoding)
                : "Binary data";
    }

    public Boolean isFile() {
        return isFile;
    }

    public boolean isBinary() {
        return encoding == null || data == null;
    }

    public String fileName() {
        return fileName;
    }

    public static RequestBody create(String data) {
        return new RequestBody(data.getBytes());
    }

    public static RequestBody create(String data, Charset charset) {
        return new RequestBody(data.getBytes(charset), charset);
    }

    public static RequestBody create(byte[] data) {
        return new RequestBody(data);
    }

    public static RequestBody create(byte[] data, String fileName) {
        return new RequestBody(data, fileName);
    }

    public static RequestBody create(byte[] data, Charset charset) {
        return new RequestBody(data, charset);
    }

    public static RequestBody empty() {
        return new RequestBody();
    }

}